package com.zhiqianbao.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.zhiqianbao.utils.Digests;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.User;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.ScreenManager;
import com.zhiqianbao.utils.ValidateUtils;
import com.zx.android.api.ConfigureObject;
import com.zx.android.api.ZXApi;
import java.util.HashMap;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2015/12/29.
 */
public class ChangePhoneActivity extends BaseActivity {
    /**
     * 原手机号
     */
    EditText editTextOldTelNum;
    /**
     * 密码
     */
    EditText edittextPassword;
    /**
     * 新手机号
     */
    EditText edittextNewTelNum;
    /**
     * 短信验证码
     */
    EditText edittextSmsAuthCode;
    /**
     * 短信验证码获取按钮
     */
    Button buttonObtainSmsAuthCode;
    /**
     * 确认按钮
     */
    Button buttonConfirm;

    //图形验证码
    ImageView loginCode;
    EditText edittextCode;
    private String msm_data1;
    private String SMS_CODE_TOKEN;
    /**
     * 计时器
     */
    TimeCount timeCount;
    private Gson gson = new Gson();

    ZXApi api;

    Handler smsTokenHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK :
                    Result<String> data = (Result<String>) msg.obj;
                    if(data!=null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            //最新短信token
                            msm_data1 = data.getData();
                            SMS_CODE_TOKEN = data.getData();
                            //点击短信验证码
                            if (ValidateUtils.isMobile(editTextOldTelNum.getText().toString().trim())) {
                                Map<String, String> param = new HashMap<>();
                                param.put("phone", editTextOldTelNum.getText().toString().trim());
                                param.put("token", msm_data1);
                                param.put("uuid", Constants.UUID);
                                param.put("code", edittextCode.getText().toString().trim());
                                new CodeTaskP().execute(param);
                            } else {
                                showShortToast1("请输入正确的电话号码！");
                            }

                            Log.i("SMS_CODE_TOKEN", "SMS_CODE_TOKEN : " + data.getData());
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;

            }
        }
    };

    Handler loginCodeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED :
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK :
                    Bitmap codeImage = (Bitmap) msg.obj;
                    loginCode.setImageBitmap(codeImage);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_phone);
        ScreenManager.getScreenManager().pushActivity(this);
        init();
        initView();
        gitImageCode();
    }

    private void initView() {
         editTextOldTelNum=(EditText)findViewById(R.id.editText_old_tel_num);
         edittextPassword=(EditText)findViewById(R.id.edittext_password);
         edittextNewTelNum=(EditText)findViewById(R.id.edittext_new_tel_num);
         edittextSmsAuthCode=(EditText)findViewById(R.id.edittext_sms_auth_code);
         buttonObtainSmsAuthCode=(Button)findViewById(R.id.button_obtain_sms_auth_code);
         buttonConfirm=(Button)findViewById(R.id.button_confirm);
         loginCode=(ImageView)findViewById(R.id.login_code);
         edittextCode=(EditText)findViewById(R.id.edittext_code);

        initApi();
        timeCount = new TimeCount(60000, 1000);
        ButtonListener listener = new ButtonListener();

        editTextOldTelNum.setText(Constants.LOGIN_USER.getPhone());

        buttonObtainSmsAuthCode.setOnClickListener(listener);
        buttonConfirm.setOnClickListener(listener);
        loginCode.setOnClickListener(listener);
    }

    private class ButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            String phoneOld = editTextOldTelNum.getText().toString();
            String phoneNew = edittextNewTelNum.getText().toString();
            String password = edittextPassword.getText().toString();
            String code = edittextCode.getText().toString();

            if(R.id.button_obtain_sms_auth_code==v.getId()) {
                if (StringUtils.isBlank(phoneNew)) {
                    showShortToast1("请输入新手机号");
                    return;
                }
                if (!ValidateUtils.isMobile(phoneNew)) {
                    showShortToast1("新手机号格式不正确");
                    return;
                }
                if (TextUtils.isEmpty(edittextCode.getText().toString().trim())) {
                    showShortToast1("请输入图片验证码!");
                }
                //调用发送验证码接口
                Map<String, String> param = new HashMap<>();
                param.put("phone", phoneNew);
                param.put("token", Constants.SMS_CODE_TOKEN);
                param.put("uuid", Constants.UUID);
                param.put("code", edittextCode.getText().toString().trim());
                new CodeAsyncTask().execute(param);
            }
            else if(R.id.login_code==v.getId()) {
                    getSmsToken();
                    gitImageCode();
            }
            else if(R.id.button_confirm==v.getId()){
                    if (StringUtils.isBlank(phoneOld)) {
                        showShortToast1("请输入原手机号");
                        return;
                    }
                    if (!ValidateUtils.isMobile(phoneOld)) {
                        showShortToast1("原手机号格式不正确");
                        return;
                    }
                    if(StringUtils.isBlank(password)) {
                        showShortToast1("请输入密码");
                        return;
                    }
                    if (StringUtils.isBlank(phoneNew)) {
                        showShortToast1("请输入新手机号");
                        return;
                    }
                    if (!ValidateUtils.isMobile(phoneNew)) {
                        showShortToast1("新手机号格式不正确");
                        return;
                    }
                    if (StringUtils.isBlank(code)) {
                        showShortToast1("请输入手机验证码");
                        return;
                    }
                    //调用修改手机号接口
                    String mpssword = Digests.md5(password, phoneNew, Digests.HASH_INTERATIONS);
                    Map<String, String> p = new HashMap<>();
                    String token = Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "";
//                    Long userId = Constants.LOGIN_USER.getId();
                    p.put("token", token);
                    p.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                    p.put("password", password);
                    p.put("newPassword",mpssword);
                    p.put("newPhone", phoneNew);
                    p.put("code", edittextSmsAuthCode.getText().toString().trim());
                    new ChangePhoneAsyncTask().execute(p);
            }
        }
    }

    class CodeTaskP extends  AsyncTask<Map,Void,Result>{

        @Override
        protected Result doInBackground(Map... params) {
            String  result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/registCode", params[0], ChangePhoneActivity.this);
            Result resultObject = gson.fromJson(result, Result.class);
            return resultObject;
        }

        @Override
        protected void onPostExecute(Result result) {
            if (result == null) {
                showShortToast1("连接超时");
                return;
            }
            if(Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                timeCount.start();
            } else {
                showShortToast1(result.getMsg());
            }
        }

    }

    private void getSmsToken() {
        {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Map<String, String> params = new HashMap<>();
                    String result = HttpUtils.httpPostString(Constants.API_ROOT + "/basic/getSmsToken", params, ChangePhoneActivity.this);
                    Message message = new Message();
                    if (StringUtils.isBlank(result)){
                        message.what = RESULT_CANCELED;
                    } else {
                        message.what = RESULT_OK;
                        Result<String> data = Result.fromJson(result, String.class);
                        message.obj = data;
                    }
                    smsTokenHandler.sendMessage(message);
                }
            }).start();
        }
    }

    private void gitImageCode() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                String uuid = Constants.UUID;
                Bitmap bitmap = HttpUtils.getUrlImage(Constants.API_ROOT + "/basic/code", ChangePhoneActivity.this);
                if (null == bitmap) {
                    message.what = RESULT_CANCELED;
                } else {
                    message.what = RESULT_OK;
                    message.obj = bitmap;
                }
                loginCodeHandler.sendMessage(message);
            }
        }).start();
    }

    private class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }
        @Override
        public void onTick(long millisUntilFinished) {
            buttonObtainSmsAuthCode.setClickable(false);
            buttonObtainSmsAuthCode.setText(millisUntilFinished / 1000 + "s后重新获取");
        }
        @Override
        public void onFinish() {
            buttonObtainSmsAuthCode.setText("重新获取");
            buttonObtainSmsAuthCode.setClickable(true);
        }
    }

    private class CodeAsyncTask extends AsyncTask<Map, Void, Result<HashMap>> {
        @Override
        protected Result<HashMap> doInBackground(Map... params) {
            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/registCode", params[0], ChangePhoneActivity.this);
            Result<HashMap> resultObject = gson.fromJson(result, Result.class);
            return resultObject;
        }

        @Override
        protected void onPostExecute(Result result) {
            if (result != null) {
                if (Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                    timeCount.start();
                } else {
                    gitImageCode();
                    showShortToast1(result.getMsg());
                }
            }
        }
    }
    private class ChangePhoneAsyncTask extends AsyncTask<Map, Void, Result<User>> {
        @Override
        protected void onPreExecute() {
            showWaitDialog();
        }
        @Override
        protected Result<User> doInBackground(Map... params) {
            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/changePhoneNew", params[0], ChangePhoneActivity.this);
            Result<User> resultObject = gson.fromJson(result, Result.class);
            return resultObject;
        }
        @Override
        protected void onPostExecute(Result result) {
            if (result!=null) {
                if (Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                    try {
                        showShortToast1(result.getMsg());
                        User loginUser = gson.fromJson(gson.toJson(result.getData()), User.class);

                        //真信更换手机号接口
//                        api.updateMobileNo(loginUser.getId() + "", loginUser.getPhone(), new APICallback() {
//                            @Override
//                            public void updateMobileNo_Callback(int code, String message) {
//                                super.updateMobileNo_Callback(code, message);
//                            }
//                        });

                        String token = Constants.LOGIN_USER.getToken();

                        loginUser.setToken(token);
                        Constants.LOGIN_USER = loginUser;
                        //更新数据库
                        User.deleteAll(User.class);
                        loginUser.save();
                        showShortToast1(result.getMsg());
                        api.destroy();
                        Intent intent=new Intent(ChangePhoneActivity.this,BindPhoneConfirmActivity.class);
                        intent.putExtra("intentChangePhone",true);
                        startActivity(intent);
                       // ChangePhoneActivity.this.finish();
                    } catch (Exception e) {

                    }

                } else {
                    showShortToast1(result.getMsg());
                    gitImageCode();
                }
            }
            else{
                gitImageCode();
            }
            closeWaitDialog();
        }
    }

    private void initApi() {
        api = ZXApi.getInstance();
        ConfigureObject configureObject = new ConfigureObject();
        configureObject.setAppId(Constants.CLIENT_APP_ID);
        configureObject.setAppSecret(Constants.CLIENT_APP_SECRET);
        boolean b = api.configure(this, configureObject);
        if(!b) {
            showShortToast1("初始化失败，请联系客服！");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ScreenManager.getScreenManager().popItemActivityExceptOne1(ChangePhoneActivity.class);
    }
}
